<template>
  <div>
    <div>姓名：<input type="text" v-model.trim="name" /></div>
    <div>年龄：<input type="text" v-model.number.trim="age" /></div>
    <div>
      性别：<select v-model="sex">
        <option value="0">男</option>
        <option value="1">女</option>
      </select>
    </div>
    <div><button @click="addOrupdata(id)">添加/修改</button></div>
    <div>
      <table>
        <thead>
          <tr>
            <th>序号</th>
            <th>姓名</th>
            <th>年龄</th>
            <th>性别</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody v-if="list.length">
          <tr v-for="(item, index) in list" :key="index">
            <td>{{ index + 1 }}</td>
            <td>{{ item.name }}</td>
            <td>{{ item.age }}</td>
            <td>{{ item.sex === '0' ? '男' : '女' }}</td>
            <td>
              <button @click="del(index)">删除</button>
              <button @click="bianji(index)">编辑</button>
            </td>
          </tr>
        </tbody>
        <tbody v-else>
          <tr>
            <td colspan="5">
              <span class="none">暂无数据</span>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      list: [
        {
          name: '张三',
          age: 18,
          sex: '0',
          id: 1,
        },
      ],
      name: '',
      age: '',
      sex: '',
      id: '',
    }
  },
  methods: {
    addOrupdata(id) {
      if (!this.name || this.age < 0 || !this.sex) {
        alert('输入的不合法，重新输入')
        return
      }

      console.log(id)

      if (id) {
        this.add(id)
      } else {
        this.updata()
      }

      this.name = ''
      this.age = ''
      this.sex = ''
    },
    add(id) {
      let a = {
        name: this.name,
        age: this.age,
        sex: this.sex,
        id: id,
      }
      this.list.splice(id - 1, 1, a)
      this.id = ''
    },
    updata() {
      this.list.push({
        name: this.name,
        age: this.age,
        sex: this.sex,
        id: this.list.length + 1,
      })
    },
    del(i) {
      this.list = this.list.filter((item, index) => index != i)
    },
    bianji(i) {
      this.name = this.list[i].name
      this.age = this.list[i].age
      this.sex = this.list[i].sex
      this.id = i + 1
    },
  },
}
</script>

<style lang="less">
table {
  width: 400px;
  border-spacing: 0;
  border-top: 1px solid #ccc;
  border-left: 1px solid #ccc;
  th {
    background: #f5f5f5;
  }
  tr:hover td {
    background: #f5f5f5;
  }
  td,
  th {
    border-bottom: 1px solid #ccc;
    border-right: 1px solid #ccc;
    text-align: center;
    padding: 10px;
    &.red {
      color: red;
    }
  }
}
</style>
